package com.deke.auth.service;


import cn.hutool.core.util.ObjectUtil;
import com.deke.auth.feign.SystemFeign;
import com.deke.entity.AclPermission;
import com.deke.entity.AclUser;
import com.deke.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/11/1 21:42
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class MyUserService implements UserDetailsService {
    @Autowired
    private SystemFeign systemFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查到用户信息
        Result<AclUser> result = systemFeign.queryByUsername(username);
        if (ObjectUtil.isNotNull(result)){
            AclUser aclUser = result.getData();
            Result<List<AclPermission>> listResult = systemFeign.queryPermissionByUserid(aclUser.getId());
            if (ObjectUtil.isNotNull(listResult)){
                List<AclPermission> permissions = listResult.getData();
                //根据用户id查到用户的权限
                List<SimpleGrantedAuthority> authorities = permissions.stream()
                        //过滤为空的元素
                        .filter(item -> item.getPermissionValue() != null)
                        //讲类型转换成SimpleGrantedAuthority
                        .map(item -> new SimpleGrantedAuthority(item.getPermissionValue()))
                        .collect(Collectors.toList());
                User user = new User(aclUser.getUsername(),aclUser.getPassword(),authorities);
                return user;
            }
        }
        return null;
    }
}